import axios from 'axios'
import store from '@/store'
import { getToken, getKeeperAuth,getIDaaSAuth } from '@/utils/auth'
import Cookies from 'js-cookie'
import { Notification } from 'element-ui'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 60000 // request timeout
})
function getUrlKey(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['Authorization'] = getToken()
            Cookies.set('IDaaS-Auth', getIDaaSAuth())
            // config.headers['Authorization'] = getToken(getUrlKey('username'))
            // Cookies.set('IDaaS-Auth', getIDaaSAuth(getUrlKey('username')+'key'))

            // Cookies.set('Keeper-Auth', getKeeperAuth())
            // Cookies.set('Keeper-Auth', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXBwX2FwaV9yZXNvdXJjZSIsImVudGVycHJpc2VfbW9iaWxlX3Jlc291cmNlIiwiYmZmX2FwaV9yZXNvdXJjZSJdLCJleHAiOjE2MjE0MzE3NTEsInVzZXJfbmFtZSI6IjE4MzgxOTMwNDY0IiwianRpIjoiMTQzYmU1ZWYtZWNhMS00ZjczLWE4ZGMtZjRmODQ1MmI0YWFhIiwiY2xpZW50X2lkIjoiNTI3YmIxMGZiMmE5MDI1YjkyMmMxM2NmMmQ0NWRhNTR5ZU1TMkxqVUpoQSIsInNjb3BlIjpbInJlYWQiXX0.n6tfUUwKnO2G6wjOw6EglT_kDgr6Tfa8prkHASADWaM')
        }
        // config.headers['Cookie'] = 'Keeper-Auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXBwX2FwaV9yZXNvdXJjZSIsImVudGVycHJpc2VfbW9iaWxlX3Jlc291cmNlIiwiYmZmX2FwaV9yZXNvdXJjZSJdLCJleHAiOjE2MjA4NDMyODYsInVzZXJfbmFtZSI6IjE4MzgxOTMwNDY0IiwianRpIjoiYTFhNDJkYmUtNWQ3OC00ZTczLTg2YWEtZTJlOGMzMWVmZTg3IiwiY2xpZW50X2lkIjoiNTI3YmIxMGZiMmE5MDI1YjkyMmMxM2NmMmQ0NWRhNTR5ZU1TMkxqVUpoQSIsInNjb3BlIjpbInJlYWQiXX0.3b-nBdPBdn6EF1KVhCBd4VgWrQj2Vx0DhJ3DMHegLIA'
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const code = response.data.code
         
        if (code !== 200) {
            let errtext = response.msg||response.data.msg;
            if(!errtext){
                errtext = '未知错误'
            }
            Notification.error({
                title: errtext
            })
            return Promise.reject('error')
        } else {
            if (response.data && response.data.code === 401) {
                store.dispatch('user/logout').then(() => {
                    // 用户登录界面提示
                    Cookies.set('point', '401')
                    Cookies.set('pointMsg', response.data.msg)
                    location.reload()
                })
            }
            return response.data
        }
    }, 
    error => {
        let code = 0
        try {
            code = error.response.data.status
        } catch (e) {
            if (error.toString().indexOf('Error: timeout') !== -1) {
                Notification.error({
                    title: '网络请求超时',
                    duration: 5000
                })
                return Promise.reject(error)
            }
        }
        if (code) {
            if (code === 401) {
                store.dispatch('user/logout').then(() => {
                    // 用户登录界面提示
                    Cookies.set('point', 401)
                    location.reload()
                })
            } else {
                const errorMsg = error.response.data.msg
                if (errorMsg !== undefined) {
                    Notification.error({
                        title: errorMsg,
                        duration: 5000
                    })
                }
            }
        } else {
            Notification.error({
                title: '接口请求失败',
                duration: 5000
            })
        }
        return Promise.reject(error)
    }
)


export default service